#!/usr/bin/env php
<?php
use Garden\Cli\Cli;
require "vendor/autoload.php";

$cli = new Cli();
$cli->description('OpenCore config.plist sanity checker')
    ->opt('ruleset:r', 'Rule set to check against', true, 'string')
    ->opt('markdown:m', 'Leave output in markdown format', false, 'boolean')
    ->arg('plist', 'config.plist to sanity check', true);
$args = $cli->parse($argv);

$plist = $args->getArg('plist');
$rules = $args->getOpt('ruleset');
$md = $args->getOpt('markdown');

$pd = new ParsedownExtra();

$results = function() use($plist,$rules,$md) {
               $old = set_error_handler("grabErrors");
               ob_start(function($buf) use($md) {
                   if($md) return $buf;
                   $pd = new ParsedownExtra();
                   return $pd->text($buf);
               });
               $oc = null;
               try {
                   $oc = new OpenCorePlist($plist);
               } catch (DOMException $e) {
                   echo "This config.plist contains XML syntax errors and will not parse";
               }
               if($oc) $oc->applyRules(new Rules($rules));
               ob_end_flush();
               set_error_handler($old);
};
$results();

function grabErrors($errno, $errstr, $errfile, $errline) {
    if(preg_match("@DOMDocument::load\(\): (.*?) in.*line: (\d+)@", $errstr, $match)) {
        echo $match[1]." line ".$match[2]."\n";
    }
}
